<template>
  <div class="cusAdd">
    <van-nav-bar
        :title="isDetail ? '详情' :getTitle"
        left-arrow
        left-text="返回"
        @click-left="back"/>
    <div class="wrapper">
      <van-form label-width="120" validate-first @failed="onFailed" @submit="onSubmit" style="width: 95%;">
        <div class="InfoCard">
          <van-field
              disabled
              name="fbillno"
              v-model="formObj.fbillno"
              label="单号"
          />
        </div>
        <van-notice-bar class="margin-top-10" color="#ff0000" background="#ecf9ff" left-icon="info-o">
          想删除行数据请右滑，将出现删除按钮
        </van-notice-bar>
        <div class="InfoCard">
          <div class="ClumnBar">
            <van-tag mark type="primary" size="large">代办事项</van-tag>
            <van-icon name="add" size="25" color="#1989fa" @click="handleAddTask" />
          </div>
          <div v-for="(contract, idx) in ywTaskEntryList" :key="idx">
            <div class="ClumnBar">
              <van-tag mark type="primary" round color="#1989fa">{{ idx + 1 }}</van-tag>
            </div>
            <van-swipe-cell>
              <van-field
                  disabled
                  v-model="contract.fstatusName"
                  label="状态"
                  placeholder="请选择状态"
                  readonly
                  clickable
                  @click="chooseFun('状态', columnsTasktype, 1, idx)"
              />
<!--              <van-field-->
<!--                  readonly-->
<!--                  clickable-->
<!--                  @click="choosedSjInfo(idx)"-->
<!--                  v-model="contract.sjname"-->
<!--                  label="商机名称"-->
<!--                  placeholder="请输入商机名称"-->
<!--              />-->
<!--              <van-field-->
<!--                  readonly-->
<!--                  v-model="contract.fcustomer"-->
<!--                  label="客户名称"-->
<!--                  placeholder="请输入客户名称"-->
<!--              />-->
              <van-field
                  :disabled="isDetail"
                  v-model="contract.fendtime"
                  label="计划完成日期"
                  placeholder="请输入计划完成日期"
                  readonly
                  clickable
                  @click="chooseExpDate(idx)"
              />
              <van-field
                  :disabled="isDetail"
                  v-model="contract.fname"
                  label="事项名称"
                  placeholder="请输入事项名称"
              />
              <van-field
                  :disabled="isDetail"
                  v-model="contract.fnote"
                  label="完成内容"
                  rows="2"
                  autosize
                  type="textarea"
                  placeholder="请输入完成内容"
              />
              <van-field
                  v-model="contract.finisher"
                  label="完成人"
                  placeholder="请输入完成人"
                  disabled
              />
              <van-field
                  v-model="contract.finishtime"
                  label="完成时间"
                  placeholder="请输入完成时间"
                  disabled
              />
              <van-field
                  readonly
                  name="fattachment"
                  label="附件"
              >
              </van-field>
              <div class="uploadWrapper">
                <div class="uploadItem" v-for="(upload, index) in contract.fattachment" :key="index" @click="handlePreview(upload)">{{ upload.filepath }}</div>
              </div>
              <template #right>
                <van-button :disabled="isDetail" square text="删除" type="danger" class="delete-button" @click="handleDeleteTask(idx)"/>
              </template>
            </van-swipe-cell>
            <van-divider v-if="idx != ywTaskEntryList.length - 1" :style="{ backgroundColor: '#efefef', height: '2px', margin: '8px 0' }" />
          </div>
        </div>
        <div style="margin: 16px;" v-show="!isDetail">
          <van-button :loading="loading" block type="info" native-type="submit">{{ ifNewAdd ? '提交' : '保存'}}</van-button>
        </div>
      </van-form>

      <!-- 选择弹框 -->
      <van-popup v-model="showPickerDate" position="bottom">
        <van-datetime-picker
            v-model="currentDate"
            type="date"
            title="计划完成日期"
            @confirm = "changeDate"
            @cancel="showPickerDate = false"
        />
      </van-popup>
      <!--数据字典选择-->
      <van-popup v-model="showPickerFun" position="bottom">
        <van-picker
            :title="choosetitle"
            show-toolbar
            :columns="columnsFun"
            @confirm="changeFun"
            @cancel="showPickerFun = false"
        />
      </van-popup>
    </div>
    <!--商机信息-->
    <choosed-sj-info ref="choosedSjInfo" @ok="backSjInfo"></choosed-sj-info>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { formatToString } from '@/utils/utils'
import {  queryYwTaskEntryByMainId, ywTaskListDetail, ywTaskListEdit, ywTaskListAdd,getDicts } from '@/api/api'
import { Notify } from 'vant'
import ChoosedSjInfo from "./choosedSjInfo";

export default {
  name: 'myTaskAdd',
  components: {
    ChoosedSjInfo
  },
  data () {
    return {
      curId: '',//记录数组当前id
      ftype: '',//记录下拉数据类型
      choosetitle: '',
      loading: false,
      ifNewAdd: true, // 新增还是编辑
      id: null, // 若是编辑记录id
      fbusinessid: null, //客户id
      fopportunityid: '',
      fnodeid: '',
      showPickerDate: false,
      showPickerFun: false,
      formObj: {
        fbillno: '',
      },
      currentDate: new Date(),
      columnsFun: [],
      columnsTasktype: [],
      ywTaskEntryList: [],//待办事项数据
    }
  },
  computed: {
    ...mapState({
      openId: state => state.user.openId,
      realname: state => state.user.realname,
      access_token: state => state.app.access_token,
      ticket: state => state.app.ticket,
      appId: state => state.user.appId
    }),
    isDetail: function () {
      return this.$route.params.isDetail ? true : false
    },
    getTitle: function () {
      return this.ifNewAdd ? '新增' : '编辑'
    }
  },
  watch:{
  },
  created () {
    this.ifNewAdd =  this.$route.params.isAdd
    this.id = this.$route.params.pid || ''
    this.fopportunityid = this.$route.params.fopportunityid
    this.fnodeid = this.$route.params.fnodeid
    if(!this.ifNewAdd) {
      this.getInfo()
    }
    getDicts('tasktype').then(res => {
      if(res.success) {
        this.columnsTasktype= res.result.map(item => {
          return {
            text: item.text,
            code: item.value
          }
        })
      }
    })
  },
  methods: {
    getInfo () {
      ywTaskListDetail({ id: this.id }).then(res => {
        if (res.success) {
          let obj = res.result
          this.formObj = Object.assign({}, obj)
        }
      })
      queryYwTaskEntryByMainId({ pid: this.id }).then(res => {
        if (res.success) {
          this.ywTaskEntryList = res.result.map(item => {
            let fattachment = [];
            (item.fattachment || '').split(',').map(item => {
              fattachment.push({
                filepath: item
              })
            })
            item.fattachment = fattachment
            return item
          })
        }
      })
    },
    choosedSjInfo (idx) {
      this.curId = idx
      this.$refs.choosedSjInfo.show()
    },
    backSjInfo (info) {
      console.log(info)
      let result = info.result
      this.ywTaskEntryList[this.curId].sjname = result.fname
      this.ywTaskEntryList[this.curId].fcustomer = result.fcustomer
      // this.ywTaskEntryList[this.curId].fopportunityid = result.id

    },
    handlePreview (record) {
      let url = 'http://124.221.130.190:8081/hwerJK/sys/common/static/' + record.filepath
      window.open(url)
    },
    chooseExpDate (idx) {
      this.curId = idx
      this.showPickerDate = true
    },
    changeDate () {
      this.ywTaskEntryList[this.curId].fendtime = formatToString(this.currentDate, 'Simple', '-')
      this.showPickerDate = false
    },
    chooseFun (title, columns, ftype, curId) {
      this.showPickerFun = true
      this.ftype = ftype
      this.curId = curId
      this.choosetitle = title
      this.columnsFun = columns
    },
    changeFun (value, index) {
      console.log(value, index)
      switch (this.ftype) {
        case 1:
          this.ywTaskEntryList[this.curId].fstatus = value.code
          this.ywTaskEntryList[this.curId].fstatusName = value.text
          break;
      }
      this.showPickerFun = false
    },
    handleAddTask () {
      const newData = {
        fstatus: '',
        fstatusName: '',
        sjname: '',
        fcustomer: '',
        fendtime: '',
        fname: '',
        fnote: '',
        finisher: '',
        finishtime: '',
        fopportunityid: '',
        fattachment: [],
      };
      this.ywTaskEntryList.push(newData)
    },
    handleDeleteTask (index) {
      this.ywTaskEntryList.splice(index, 1)
    },
    onFailed () { // values, errors
      Notify({ type: 'warning', message: '请将信息填写完整!', duration: 4000 })
    },
    async onSubmit () {
      this.loading = true
      let params = {
        ...this.formObj,
        id: this.id,
        ywTaskEntryList: this.ywTaskEntryList.map(item => {
          item.fopportunityid = item.fopportunityid ? item.fopportunityid :this.fopportunityid
          item.fnodeid = this.fnodeid
          item.fattachment = item.fattachment.length ? item.fattachment.map( item => item.filepath).join() : ''
          return item
        })
      }
      if (this.ifNewAdd) {
        ywTaskListAdd(params).then( res => {
          if (res.success) {
            Notify({ type: 'success', message: '待办事项新增成功!', duration: 4000 })
            this.back()
            this.loading = false
          }else {
            Notify({ type: 'danger', message: res.result, duration: 4000 })
            this.loading = false
          }
        })
      } else {
        ywTaskListEdit(params).then(res => {
          if (res.success) {
            Notify({ type: 'success', message: '待办事项修改成功!', duration: 4000 })
            this.back()
            this.loading = false
          }
        })
      }

    },
    back () {
      this.$router.push({name: 'myTaskList', params: { fopportunityid: this.fopportunityid }})
    }
  }
}
</script>
<style scoped>
.wrapper{
  background: #efefef;
  display: flex;
  justify-content: center;
}
.ContactOption{
  margin-bottom: 5px;
}
.ClumnBar{
  height: 30px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.delete-button {
  height: 100% !important;
}
.uploadWrapper {
  display: flex;
  flex-direction: column;
  color: #1989fa;
  font-size: 14px;
  margin-bottom: 2px;
}
.uploadItem {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>

